import { z } from 'zod';
import { Context } from 'koa';

export function validateBody<T extends z.ZodType>(schema: T) {
  return async (ctx: Context, next: () => Promise<void>) => {
    try {
      ctx.state.validatedBody = await schema.parseAsync(ctx.request.body);
      return next();
    } catch (err) {
      if (err instanceof z.ZodError) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: 'Validation failed',
          errors: err.errors,
        };
        return;
      }
      throw err;
    }
  };
}

export function validateQuery<T extends z.ZodType>(schema: T) {
  return async (ctx: Context, next: () => Promise<void>) => {
    try {
      ctx.state.validatedQuery = await schema.parseAsync(ctx.query);
      return next();
    } catch (err) {
      if (err instanceof z.ZodError) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: 'Validation failed',
          errors: err.errors,
        };
        return;
      }
      throw err;
    }
  };
}
